<template>
    <view>
        <!-- pages/index/index.wxml -->
        <view class="container">
            <!-- 自定义导航栏 -->
            <custom-navbar :showTitle="true" backgroundColor="transparent" textColor="#ffffff" :showBack="false"
                :isHomePage="true" ref="customNavbar"></custom-navbar>
            <!-- 主要内容区域 -->
            <view class="main-content" :style="'height: ' + contentHeight + 'px;'">
                <!-- 主背景图片区域 -->
                <view class="hero-section">
                    <image class="hero-image" src="https://image.shengxuankj.com/fronts/bannerIndex.png"
                        mode="aspectFit" style="width: 100%; height: 100%"></image>
                </view>
                <!-- 搜索和预订区域 -->
                <view class="booking-section">
                    <!-- 预订卡片容器 -->
                    <view class="booking-card">
                        <!-- 房间类型选择 -->
                        <view class="room-type-tabs">
                            <view class="tab-item" :class="{ active: selectedRoomType === 'standard' }"
                                @tap="selectRoomType('standard')">
                                <text>山也客房</text>
                            </view>
                            <view class="tab-item" :class="{ active: selectedRoomType === 'pet' }"
                                @tap="selectRoomType('pet')">
                                <text>宠物友好房</text>
                            </view>
                        </view>
                        <!-- 搜索框 -->
                        <!-- 日期选择 -->
                        <view class="date-section" @tap="openCalendar">
                            <view class="date-item">
                                <text class="date-label">入住日期</text>
                                <view class="date-start">
                                    <text class="date-value">{{ checkInDate || '选择日期' }}</text>
                                    <text class="date-day" v-if="checkInWeek">{{ checkInWeek }}</text>
                                </view>
                            </view>
                            <view class="date-divider">{{ nights }}晚</view>
                            <view class="date-item">
                                <text class="date-label">离店日期</text>
                                <view class="date-end">
                                    <text class="date-value">{{ checkOutDate || '选择日期' }}</text>
                                    <text class="date-day" v-if="checkOutWeek">{{ checkOutWeek }}</text>
                                </view>
                            </view>
                            <view class="date-select-icon">📅</view>
                        </view>
                        <!-- 预订按钮 -->
                        <button class="booking-btn" @tap="onBooking">开启住宿</button>
                    </view>
                    <view class="main-content-excessive">
                        <image src="https://image.shengxuankj.com/fronts/homeNext.png" mode=""
                            :class="isImageAnimating ? 'bounce-animation' : ''" />
                    </view>
                    <!-- 民宿故事 -->
                    <up-sticky :offsetTop="stickyNavBarHeight">
                        <view class="recommendations">
                            <view class="section-title">
                                <text>民宿故事</text>
                                <text></text>
                            </view>
                            <!-- 故事列表 -->
                            <Pinterest :height="contentHeight - navBarHeight - rpxToPx(stickyNavBarHeight)" :items="stories" :isLoading="isLoading"
                            :hasMore="hasMore" @itemClick="handleStoryClick" @loadMore="loadMoreFun" />
                        </view>
                    </up-sticky>
                </view>
            </view>
        </view>
        <!-- 日历组件弹窗 -->
        <!-- <up-popup :show="showPopup" mode="bottom" border-radius="20" :closeOnClickOverlay="true" @close="closeCalendar" :closeable="true"> -->
        <!-- <view class="calendar-popup"> -->
        <!-- <view class="calendar-header">
                    <text class="calendar-title">选择入住和离店日期</text>
                    <up-icon name="close" @tap="closeCalendar" class="close-icon"></up-icon>
                </view> -->
        <up-calendar :show="showCalendar" :closeOnClickOverlay="true" @close="closeCalendar" :mode="mode" round="20"
            startText="住店" endText="离店" confirmDisabledText="请选择离店日期" :formatter="formatter" @confirm="selectDate"
            :defaultDate="defaultDateMultiple"></up-calendar>
        <!-- </view> -->
        <!-- </up-popup> -->

    </view>
</template>

<script setup lang="ts">
    import { ref, onMounted, toRaw } from 'vue'
    import { onShow, onReady } from '@dcloudio/uni-app';
    import customNavbar from '@/components/custom-navbar/index'
    import { postListFun } from '@/api/port'
    import Pinterest from '../../components/Pinterest/index.vue';
    // 房间类型选择
    const selectedRoomType = ref<string>('standard')
    // 类型定义
    interface Story {
        [key: string]: any;
    }

    interface TouchEvent {
        currentTarget: {
            dataset: {
                story: Story;
            };
        };
    }
    // 日历相关数据
    const mode = ref('range')
    // 格式化日期，显示为yyyy-MM-dd
    const formatter = (day) => {
        const d = new Date();
        let month = d.getMonth() + 1;
        const date = d.getDate();
        return day;
    };
    const showCalendar = ref<boolean>(false)
    const showPopup = ref<boolean>(false)
    const selectedDates = ref<string[]>([])
    const defaultDateMultiple = ref<string[]>([])
    const closeCalendar = () => {
        // showPopup.value = false
        showCalendar.value = false
    }
    const checkInDate = ref<string>('')
    const checkOutDate = ref<string>('')
    const checkInWeek = ref<string>('')
    const checkOutWeek = ref<string>('')
    const nights = ref<number>(0)
    const calculateNights = () => {
        if (checkInDate.value && checkOutDate.value) {
            const checkIn = new Date(checkInDate.value)
            const checkOut = new Date(checkOutDate.value)
            const diffTime = checkOut.getTime() - checkIn.getTime()
            nights.value = Math.ceil(diffTime / (1000 * 60 * 60 * 24))
        }
    }
    // 选择日期
    const selectDate = (dates: string[]) => {
        selectedDates.value = dates
        if (dates.length >= 2) {
            checkInDate.value = dates[0]
            checkOutDate.value = dates[dates.length - 1]
            calculateNights()
            // 计算入住周几
            const checkInDay = new Date(checkInDate.value)
            checkInWeek.value = Weekday[checkInDay.getDay() as Weekday]
            // checkInWeek.value = checkInDay.toLocaleDateString('zh-CN', { weekday: 'long' })
            // 计算离店周几
            const checkOutDay = new Date(checkOutDate.value)
            checkOutWeek.value = Weekday[checkOutDay.getDay() as Weekday]
            // checkOutWeek.value = checkOutDay.toLocaleDateString('zh-CN', { weekday: 'long' })
        }
        closeCalendar()
    }
    // 打开日历弹窗
    const openCalendar = () => {
        showPopup.value = true
        showCalendar.value = true
    }
    // 首次进入页面获取默认日期，今天为入住日期，明天为离店日期，并为日历设置默认日期
    const getDefaultDate = () => {
        const today = new Date()
        const tomorrow = new Date(today)
        tomorrow.setDate(tomorrow.getDate() + 1)
        checkInDate.value = today.toISOString().split('T')[0]
        checkOutDate.value = tomorrow.toISOString().split('T')[0]
        calculateNights()
        // 计算入住周几
        const checkInDay = new Date(checkInDate.value)
        // 计算离店周几
        const checkOutDay = new Date(checkOutDate.value)
        // 计算入住周几
        checkInWeek.value = Weekday[checkInDay.getDay()]
        // 计算离店周几
        checkOutWeek.value = Weekday[checkOutDay.getDay()]
        // 为日历设置默认日期
        defaultDateMultiple.value = [checkInDate.value, checkOutDate.value]
        console.log(defaultDateMultiple.value)
    }
    /**
     * 日期格式化 
     * @param date 日期
     * @returns 格式化后的日期
     */
    const formatDate = (date: string) => {
        const d = new Date(date)
        const month = d.getMonth() + 1
        const day = d.getDate()
        return `${month}月${day}日`
    }

    /**
     * 枚举星期
     */
    const Weekday = {
        1: '星期一',
        2: '星期二',
        3: '星期三',
        4: '星期四',
        5: '星期五',
        6: '星期六',
        7: '星期日',
    }
    /**
     * 选择房间类型
     * @param type 
     */
    // 选择房间类型
    const selectRoomType = (type: string) => {
        selectedRoomType.value = type
    }

    const navBarHeight = ref<number>(0)
    const stickyNavBarHeight = ref<number>(0)
    const tabBarHeight = ref<number>(0)
    const contentHeight = ref<number>(0)
    const isImageAnimating = ref<boolean>(true)

    // 民宿故事列表
    const stories = ref<any[]>([])
    const isLoading = ref<boolean>(false)
    const hasMore = ref<boolean>(true)
    const totalPages = ref<number>(0)

    /**
     * 分页参数
     */
    const pageParams = ref({
        page_no: 1,
        page_size: 10,
    })
    /**
     * 调用接口获取故事列表
     * @param {boolean} isLoadMore 是否为加载更多
     * @returns 
     */
    const getStoryList = async (isLoadMore: boolean = false) => {
        if (isLoading.value) return;

        isLoading.value = true;

        try {
            const res = await postListFun({
                page_no: pageParams.value.page_no,
                page_size: pageParams.value.page_size,
            });

            if (res.code === 1) {
                const newStories = res.data.list || [];
                totalPages.value = Math.ceil(res.data.total / pageParams.value.page_size) || 0;

                if (isLoadMore) {
                    // 加载更多，追加数据
                    stories.value = [...stories.value, ...newStories];
                } else {
                    // 首次加载，替换数据
                    stories.value = newStories;
                }

                // 检查是否还有更多数据
                hasMore.value = pageParams.value.page_no < totalPages.value;

                if (newStories.length > 0 && hasMore.value) {
                    pageParams.value.page_no++;
                }
            } else {
                uni.showToast({
                    title: res.msg || '获取数据失败',
                    icon: 'none',
                    duration: 2000
                });
            }
        } catch (error) {
            console.error('获取故事列表失败:', error);
            uni.showToast({
                title: '网络错误，请重试',
                icon: 'none',
                duration: 2000
            });
        } finally {
            isLoading.value = false;
        }
    }
    
    const handleStoryClick = (e: TouchEvent) => {
        goToStoryDetail(e);
    }
    // 跳转到故事详情
    const goToStoryDetail = (e: TouchEvent): void => {
        console.log(e)
        const story = e
        uni.showToast({
            title: '查看故事：' + story.title,
            icon: 'none',
            duration: 2000
        });
        // 这里可以跳转到故事详情页面
        uni.navigateTo({
            url: '/subpackage/talesDetail/talesDetail?id=' + story.id,
        })
    };
    /**
     * 上拉加载更多
     */
    const loadMoreFun = async () => {
        if (isLoading.value || !hasMore.value) {
            return;
        }

        console.log('触发上拉加载，当前页:', pageParams.value.page_no);
        await getStoryList(true);
    }

    onShow(() => {
        getStoryList(false);
    })


    const canIUseGetUserProfile = ref<boolean>(false)
    const showGenderPopup = ref<boolean>(false)
    // 页面加载时执行
    const onPageLoad = (): void => {
        if (uni.getUserProfile) {
            canIUseGetUserProfile.value = true
        }
        // 计算剩余可视高度
        calculateContentHeight()

        getDefaultDate()
    }

    // 用户点击右上角分享
    const onPageShareAppMessage = () => {
        return {
            title: '山居民宿 - 远离expensive，静享自然',
            path: '/pages/index/index',
            imageUrl:
                'https://images.unsplash.com/photo-1506905925346-21bda4d32df4?ixlib=rb-4.0.3&ixid=M3wxMjA3fDB8MHxwaG90by1wYWdlfHx8fGVufDB8fHx8fA%3D%3D&auto=format&fit=crop&w=500&q=80'
        }
    }
    // 计算主要内容区域的高度
    const calculateContentHeight = (): void => {
        const systemInfo = uni.getWindowInfo()
        const windowHeight = systemInfo.windowHeight
        const safeAreaBottom = systemInfo.safeArea ? systemInfo.screenHeight - systemInfo.safeArea.bottom : 0
        const tabBarHeightValue = 50 + safeAreaBottom // 自定义tabbar高度(100rpx转px约50px) + 安全区域

        // 首页导航栏不占用空间，所以内容高度就是窗口高度减去tabbar高度
        const contentHeightValue = windowHeight
        tabBarHeight.value = tabBarHeightValue
        contentHeight.value = contentHeightValue
    }

    /**
     * 预订按钮点击事件
     */
    const onBooking = (): void => {
        if (selectedRoomType.value === 'standard') {
            uni.navigateTo({
                url: `/subpackage/rooms/rooms?checkInDate=${checkInDate.value}&checkOutDate=${checkOutDate.value}`
            })
        } else if (selectedRoomType.value === 'pet') {
            uni.navigateTo({
                url: `/subpackage/petRooms/petRooms?checkInDate=${checkInDate.value}&checkOutDate=${checkOutDate.value}`
            })
        } else {
            uni.showToast({
                title: '请选择房间类型',
                icon: 'none'
            })
        }
    }

    /**
     * 搜索民宿
     */
    const onSearch = (): void => {
        const options = {
            title: '搜索功能开发中',
            icon: 'none'
        }
        uni.showToast(options)
    }

    /**
     * 跳转到日志页面
     */
    const goToLogs = (): void => {
        uni.navigateTo({
            url: '/packageB/pages/logs/logs'
        })
    }

    /**
     * 跳转到个人资料页面
     */
    const goToProfile = (): void => {
        uni.navigateTo({
            url: '/pages/profile/profile'
        })
    }

    /**
     * 跳转到设置页面
     */
    const goToSettings = (): void => {
        uni.navigateTo({
            url: '/subpackage/pages/settings/settings'
        })
    }

    /**
     * 跳转到订单页面
     */
    const goToOrders = (): void => {
        uni.navigateTo({
            url: '/packageB/pages/order/order'
        })
    }

    // 计算，px的值转成rpx 的值（标准转换）
    const pxToRpx = (px: number): number => {
        const systemInfo = uni.getWindowInfo()
        return Number((px / systemInfo.screenWidth * 750).toFixed(2))
    }

    // 计算，rpx 的值转成px 的值（标准转换）
    const rpxToPx = (rpx: number): number => {
        const systemInfo = uni.getWindowInfo()
        return Number((rpx / 750 * systemInfo.screenWidth).toFixed(2))
    }

    // 页面挂载时执行
    onMounted(() => {
        onPageLoad()
        navBarHeight.value = uni.getStorageSync('navHeight') ? uni.getStorageSync('navHeight') : 88;
        stickyNavBarHeight.value = uni.getStorageSync('navHeight') ? pxToRpx(uni.getStorageSync('navHeight')) : pxToRpx(88);
    })

</script>
<style>

    /**pages/index/index.wxss**/
    page {
        background-color: #ffffff;
        height: 100vh;
    }

    .container {
        position: relative;
        height: 100vh;
        display: flex;
        flex-direction: column;
    }

    /* 主要内容区域 */
    .main-content {
        width: 100%;
        position: relative;
        overflow-y: auto;
        /* display: flex; */
    }

    /* 主背景区域 */
    .hero-section {
        position: relative;
        /* height: calc(100% - 100px - 56px); */
        height: 1102rpx;
        overflow: hidden;
        flex-shrink: 0;
    }

    /* 日历弹窗样式 */
    .calendar-popup {
        width: 680rpx;
        background: #ffffff;
        border-radius: 20rpx;
        overflow: hidden;
    }

    .calendar-header {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 30rpx 40rpx 20rpx;
        border-bottom: 1rpx solid #f0f0f0;
    }

    .calendar-title {
        font-size: 32rpx;
        font-weight: 600;
        color: #333333;
    }

    .close-icon {
        font-size: 40rpx;
        color: #999999;
        cursor: pointer;
    }

    .calendar-footer {
        padding: 30rpx 40rpx;
        border-top: 1rpx solid #f0f0f0;
    }

    .calendar-footer .u-button {
        width: 100%;
        height: 80rpx;
        border-radius: 40rpx;
        font-size: 30rpx;
    }

    /* 日期选择区域增加点击效果 */
    .date-section {
        cursor: pointer;
        transition: all 0.2s ease;
    }

    .date-section:active {
        transform: scale(0.98);
        opacity: 0.8;
    }

    .hero-image {
        width: 100%;
        height: 100%;
    }

    .hero-content {
        position: absolute;
        left: 60rpx;
        bottom: 80rpx;
        color: white;
    }

    .main-title {
        font-size: 80rpx;
        font-weight: 300;
        line-height: 1;
        margin-bottom: 10rpx;
        text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.3);
    }

    .sub-title {
        font-size: 80rpx;
        font-weight: 300;
        line-height: 1;
        margin-bottom: 20rpx;
        text-shadow: 0 4rpx 8rpx rgba(0, 0, 0, 0.3);
    }

    .description {
        display: flex;
        flex-direction: column;
        gap: 4rpx;
    }

    .desc-line {
        font-size: 24rpx;
        color: rgba(255, 255, 255, 0.9);
        text-shadow: 0 2rpx 4rpx rgba(0, 0, 0, 0.3);
    }

    /* 搜索和预订区域 */
    .booking-section {
        /* flex: 1; */
        border-radius: 40rpx 40rpx 0 0;
        padding: 0rpx 30rpx 40rpx 30rpx;
        padding-bottom: 40rpx;
        position: absolute;
        top: calc(1102rpx - 100rpx);
        left: 0;
        right: 0;
        z-index: 10;
        overflow-y: auto;
    }

    /* 预订卡片容器 */
    .booking-card {
        /* margin: 0 30rpx; */
        padding: 40rpx 20rpx;
        background-color: white;
        border-radius: 20rpx;
        box-shadow: 0 8rpx 24rpx rgba(0, 0, 0, 0.1), 0 4rpx 8rpx rgba(0, 0, 0, 0.06), 0 2rpx 4rpx rgba(0, 0, 0, 0.04);
        /* margin-bottom: 40rpx; */
    }

    /* 房间类型选择器 */
    .room-type-tabs {
        display: flex;
        background-color: #f5f5f5;
        border-radius: 12rpx;
        padding: 6rpx;
        margin-bottom: 30rpx;
    }

    .tab-item {
        flex: 1;
        text-align: center;
        padding: 16rpx 20rpx;
        border-radius: 8rpx;
        transition: all 0.3s ease;
        cursor: pointer;
    }

    .tab-item text {
        font-size: 28rpx;
        color: #666;
        font-weight: 500;
    }

    .tab-item.active {
        background-color: #396136;
        box-shadow: 0 2rpx 8rpx rgba(57, 97, 54, 0.3);
    }

    .tab-item.active text {
        color: white;
    }

    /* 搜索框 */
    .search-box {
        display: flex;
        align-items: center;
        background-color: #f8f8f8;
        border-radius: 50rpx;
        padding: 24rpx 32rpx;
        margin-bottom: 30rpx;
    }

    .search-icon {
        font-size: 32rpx;
        margin-right: 20rpx;
        color: #999;
    }

    .search-input {
        flex: 1;
        font-size: 28rpx;
        color: #333;
    }

    /* 日期选择 */
    .date-section {
        display: flex;
        align-items: center;
        justify-content: space-between;
        margin-bottom: 30rpx;
        padding: 20rpx;
        background-color: #f8f9fa;
        border-radius: 16rpx;
        border: 2rpx solid #e9ecef;
        transition: all 0.3s ease;
        position: relative;
    }

    .date-section:active {
        background-color: #e9ecef;
        border-color: #4caf50;
    }

    .date-item {
        display: flex;
        flex-direction: column;
        align-items: center;
        gap: 10rpx 0;
        flex: 1;
    }

    .date-start {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        gap: 4rpx;
    }

    .date-end {
        display: flex;
        align-items: center;
        justify-content: center;
        flex-direction: column;
        gap: 4rpx;
    }

    .date-label {
        font-size: 26rpx;
        color: #666;
        margin-bottom: 8rpx;
        font-weight: 500;
    }

    .date-value {
        font-size: 34rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 4rpx;
        text-align: center;
    }

    .date-day {
        font-size: 24rpx;
        color: #666;
        text-align: center;
    }

    .date-divider {
        font-size: 28rpx;
        color: #4caf50;
        font-weight: 600;
        background-color: #e8f5e8;
        padding: 8rpx 16rpx;
        border-radius: 20rpx;
        margin: 0 20rpx;
    }

    .date-select-icon {
        position: absolute;
        top: 10rpx;
        right: 15rpx;
        font-size: 24rpx;
        opacity: 0.6;
        animation: pulse 2s infinite;
    }

    @keyframes pulse {
        0% {
            opacity: 0.6;
        }

        50% {
            opacity: 1;
        }

        100% {
            opacity: 0.6;
        }
    }

    /* 预订按钮 */
    .booking-btn {
        width: 100% !important;
        height: 76rpx;
        background: linear-gradient(135deg, #4caf50, #45a049);
        color: white;
        border: none;
        border-radius: 48rpx;
        font-size: 32rpx;
        font-weight: 600;
        display: flex;
        align-items: center;
        justify-content: center;
        margin-bottom: 0;
        margin: 0 !important;
        box-shadow: 0 4rpx 12rpx rgba(76, 175, 80, 0.3);
        transition: all 0.3s ease;
    }

    .booking-btn:active {
        background: linear-gradient(135deg, #45a049, #3d8b40);
        transform: translateY(2rpx);
        box-shadow: 0 2rpx 8rpx rgba(76, 175, 80, 0.4);
    }

    .booking-btn:disabled {
        background: #cccccc !important;
        color: #999999 !important;
        box-shadow: none !important;
    }

    /* 推荐区域 */
    .recommendations {
        margin-top: 20rpx;
    }

    .section-title {
        width: 100%;
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        margin-bottom: 30rpx;
    }

    .section-title text:nth-child(1) {
        font-size: 32rpx;
        font-weight: 600;
        color: rgba(14, 82, 9, 1);
        margin-bottom: 20rpx;
    }

    .section-title text:nth-child(2) {
        width: 64rpx;
        height: 4rpx;
        background-color: rgba(14, 82, 9, 1);
    }

    /* 民宿故事样式 */
    .story-list {
        display: flex;
        flex-direction: column;
        gap: 20rpx;
    }

    .story-item {
        width: 100%;
    }

    .story-item-view {
        width: 100%;
        display: flex;
        align-items: flex-start;
        justify-content: space-between;
        margin-bottom: 30rpx;
    }

    .story-item-view .story-item-view-left {
        width: calc(100% - 92rpx);
    }

    .story-item-view .story-item-view-left .story-image {
        width: 100%;
        height: 234rpx;
        border-radius: 10rpx;
    }

    .story-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;
    }

    .story-title {
        font-size: 28rpx;
        font-weight: 600;
        color: #333;
        margin-bottom: 8rpx;
    }

    .story-desc {
        font-size: 24rpx;
        color: #666;
        line-height: 1.4;
        margin-bottom: 8rpx;
    }

    .story-date {
        font-size: 22rpx;
        color: #999;
    }

    .story-item-view-right {
        width: 70rpx;
        height: 234rpx;
        background-color: rgba(57, 97, 54, 1);
        /* 关键属性：设置文字方向为垂直 */
        writing-mode: vertical-rl;
        /* 从右到左垂直排列 */

        /* 可选：调整文字间距 */
        letter-spacing: 10rpx;
        /* 可选：设置容器高度以适应内容 */
        text-align: center;
        display: flex;
        align-items: center;
        justify-content: center;
        color: #ffffff;
        border-radius: 42rpx;
    }

    .main-content-excessive {
        margin: 80rpx 0;
        width: 100%;
        display: flex;
        align-items: center;
        justify-content: center;
    }

    .main-content-excessive image {
        width: 24rpx;
        height: 32rpx;
    }

    /* 跳动动画 */
    .bounce-animation {
        animation: bounce 1s ease-in-out infinite;
    }

    @keyframes bounce {

        0%,
        100% {
            transform: translateY(0);
        }

        50% {
            transform: translateY(-10rpx);
            /* 5px = 10rpx */
        }
    }
</style>
